<template>
	<view>
		<view class="cu-list menu-avatar">
			<view v-if="data.message_list.length == 0">
				<view class="text-center text-grey margin padding">
					暂无消息...
				</view>
			</view>
			<view class="cu-item" v-for="item in data.message_list" :key="item.id" @tap="goChat(item)">
				<view class="cu-avatar radius lg" :style="'background-image:url(' + item.active_user.avatar + ')'"></view>
				<view class="content">
					<view class="text-pink">
						<view class="text-cut">{{ item.active_user.nickname }}</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">{{ item.last_message }}</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">{{ item.timestamp }}</view>
					<view v-if="item.message_count > 0" class="cu-tag round bg-red sm">{{ item.message_count }}</view>
				</view>
			</view>

			<!-- <view class="cu-item">
				<view class="cu-avatar radius lg"
					style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg);">
				</view>
				<view class="content">
					<view class="text-grey">凯尔</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">
							<text class="cuIcon-infofill text-red  margin-right-xs"></text>
							我已天理为凭，踏入这片荒芜，不再受凡人的枷锁遏制。我已天理为凭，踏入这片荒芜，不再受凡人的枷锁遏制。
						</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">22:20</view>
					<view class="cu-tag round bg-grey sm">5</view>
				</view>
			</view>
			<view class="cu-item">
				<view class="cu-avatar radius lg"
					style="background-image:url(https://ossweb-img.qq.com/images/lol/img/champion/Taric.png);">
					<view class="cu-tag badge">99+</view>
				</view>
				<view class="content">
					<view class="text-grey">
						<view class="text-cut">瓦洛兰之盾-塔里克</view>
						<view class="cu-tag round bg-orange sm">战士</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">
							塔里克是保护者星灵，用超乎寻常的力量守护着符文之地的生命、仁爱以及万物之美。塔里克由于渎职而被放逐，离开了祖国德玛西亚，前去攀登巨神峰寻找救赎，但他找到的却是来自星界的更高层的召唤。现在的塔里克与古代巨神族的神力相融合，以瓦洛兰之盾的身份，永不疲倦地警惕着阴险狡诈的虚空腐化之力。
						</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">22:20</view>
					<view class="cuIcon-notice_forbid_fill text-gray"></view>
				</view>
			</view>
			<view class="cu-item ">
				<view class="cu-avatar radius lg"
					style="background-image:url(https://ossweb-img.qq.com/images/lol/img/champion/Morgana.png);"></view>
				<view class="content">
					<view class="text-pink">
						<view class="text-cut">莫甘娜</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">凯尔，你被自己的光芒变的盲目！</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">22:20</view>
					<view class="cu-tag round bg-red sm">5</view>
				</view>
			</view>
			<view class="cu-item grayscale">
				<view class="cu-avatar radius lg"
					style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big81007.jpg);">
				</view>
				<view class="content">
					<view>
						<view class="text-cut">伊泽瑞尔</view>
						<view class="cu-tag round bg-orange sm">断开连接...</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut"> 等我回来一个打十个</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">22:20</view>
					<view class="cu-tag round bg-red sm">5</view>
				</view>
			</view>
			<view class="cu-item cur">
				<view class="cu-avatar radius lg"
					style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big81020.jpg);">
					<view class="cu-tag badge"></view>
				</view>
				<view class="content">
					<view>
						<view class="text-cut">瓦罗兰大陆-睡衣守护者-新手保护营</view>
						<view class="cu-tag round bg-orange sm">6人</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut"> 伊泽瑞尔：<text class="cuIcon-locationfill text-orange margin-right-xs"></text> 传送中...
						</view>
					</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">22:20</view>
					<view class="cuIcon-notice_forbid_fill text-gray"></view>
				</view>
			</view> -->
		</view>
	</view>
</template>

<script>
import loginjs from '../../core/login'

export default {
	data() {
		return {
			data: {
				onMessageListPage: true, //是否在消息列表页
				socketOpen: false, //是否开启了websocket
				current_passive_uid: -1, //当前聊天对象
				heartbeat_delay: 50000, //心跳时间
				message_page: 1, //当前消息列表页面，每页20个列表
				message_list: [], //用于渲染的消息列表数据
				unreadcount: 0, //总未读消息数
				reconnect_delay: 5000, //重连延迟
				eventChannel: null //与chat的通信接口

			},
			loginFlag: true,//判断是否登录
		};
	},
	mounted() {
	},
	onShow() {
		this.data.onMessageListPage = true
		this.current_passive_uid = -1
	},
	onLoad(options) {
		this.islogin()//判断是否登录
		// setTimeout(() => {
		// 	uni.$emit('eventName', 'isok')
		// 	console.log('触发了EMIT事件')
		// }, 3000)
		this.getChatList()
		this.openWebSocket()

	},
	methods: {
		islogin() {

			if (loginjs.checkIfLogin() == false) {
				this.loginFlag = false
				// 弹窗提示请登录后操作
				uni.showToast({
					title: '请先登录',
					icon: 'none',
					mask: true,
					duration: 1000,
				})

				uni.reLaunch({
					url: '/pages/auth/login/index'
				})

			}


		},
		goChat(item) {
			this.data.onMessageListPage = false
			this.current_passive_uid = item.active_uid
			uni.navigateTo({
				url: '/pages/chatPage/chatPage?nickname=' + item.active_user.nickname + '&p_uid=' + item.active_uid
			})
		},
		getChatList() {
			if (!this.loginFlag) {
				return
			}
			this.$myHttp.get({
				url: this.$myHttp.urlMap.getChatList + '?page=1&limit=1000',
				needLogin: true,
				success: res => {
					this.data.message_list = res.data.data.data
				}
			})
		},
		// 	    url: 'wss://kehu.ruoyiweb.hellomky.cn/wss',

		// openWebSocket(){

		// 	wx.connectSocket({
		// 	    url: this.$myHttp.urlMap.chat,
		// 	    header: {
		// 	        'content-type': 'application/json',
		// 	        'from': 'wechatmini'
		// 	    },

		// 	    success: function(res) {
		// 	        console.log('WebSocket 连接成功', res);

		// 	           },
		// 	    fail: function(err) {

		// 	        console.error('WebSocket 连接失败', err);
		// 	    }
		// 	});
		// },
		openWebSocket() {
			if (!this.loginFlag) {
				return
			}
			let that = this
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;
			console.log('%c [ tokenValue ]-182', 'font-size:13px; background:pink; color:#bf2c9f;', tokenValue)

			// wx.connectSocket({
			// 	// url: app.globalData.wss_url,
			// 	url: that.$myHttp.urlMap.chat,
			// 	header: {
			// 		'content-type': 'application/json',
			// 		'from': 'wechatmini'
			// 	},
			// 	success: function (res) {
			// 		console.log('WebSocket 连接成功', res);

			// 	},
			// 	fail: function (err) {

			// 		console.error('WebSocket 连接失败', err);
			// 	}
			// })
			wx.connectSocket({
				url: that.$myHttp.urlMap.chat,
				header: {
					'content-type': 'application/json',
					'from': 'wechatmini'
				}
			})
			wx.onSocketMessage((msg) => {
				let data = JSON.parse(msg.data)
				console.log('webdata: ', data)
				switch (data.data.type) {
					case 'new_message':
						//我接收消息
						console.log('收到new_message')
						//接到新消息时，在消息列表页面，刷新消息列表
						if (that.data.onMessageListPage) {
							this.getChatList()
							// this.$myHttp.get({
							// 	url: that.$myHttp.urlMap.receiveMsg,
							// 	data: {
							// 		limit: 10,
							// 		page: 1
							// 	},
							// 	success: res => {
							// 		for (let i = 0, n = res.data.errDetail.length; i < n; i++) {
							// 			res.data.errDetail[i].date = dateTrans(new Date(parseInt(
							// 				res.data.errDetail[i].timestamp)), new Date())
							// 		}
							// 		//console.log(res.data.errDetail)
							// 		that.setData({
							// 			message_list: res.data.errDetail
							// 		})
							// 	}
							// })
							//接到消息时，在聊天页面，如果发消息的是正在聊天的对象，则将新消息传给聊天页
						}

						else {
							// const newMsg = data.errDetail.new_message
							// if (newMsg.active_uid == that.data.current_passive_uid) {
							// 	that.data.eventChannel.emit('newMsgChannel', {
							// 		data: newMsg
							// 	})
							// }
							//刷新

							uni.$emit('refash')
							console.log('触发了刷新了消息')


						}
						break;
					case 'message_send':
						// 我发送消息
						console.log('message_send')

						// const newMsg = data.errDetail.message_send
						// that.data.eventChannel.emit('messageSendChannel', {
						// 	data: newMsg
						// })
						break;

				}
			})
			wx.onSocketOpen((msg) => {
				that.data.socketOpen = true
				that.sendMsg({
					type: 'login',
					token: tokenValue
				})
				console.log('WebSocket登录')
				//心跳
				that.data.pong = setInterval(() => {
					that.sendMsg({
						type: 'pong'
					})
				}, that.data.heartbeat_delay);
			})
			wx.onSocketClose((msg) => {
				clearInterval(that.data.pong)
				//reconnect
				that.data.socketOpen = false
				let i = setInterval(() => {
					wx.connectSocket({
						url: that.$myHttp.urlMap.chat,
						header: {
							'content-type': 'application/json',
							'from': 'wechatmini'
						}
					})
					console.log('reconnect')
					if (that.data.socketOpen) clearInterval(i)
				}, that.data.reconnect_delay)
			})
		},

		sendMsg(data) {
			wx.sendSocketMessage({
				data: JSON.stringify(data)
			})
		},
		// ListTouch触摸开始
		ListTouchStart(e) {
			this.listTouchStart = e.touches[0].pageX
		},

		// ListTouch计算方向
		ListTouchMove(e) {
			this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
		},
		// ListTouch计算滚动
		ListTouchEnd(e) {
			if (this.listTouchDirection == 'left') {
				this.modalName = e.currentTarget.dataset.target
			} else {
				this.modalName = null
			}
			this.listTouchDirection = null
		}
	}

}
</script>

<style lang="scss"></style>